import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, setToken } from '@/utils/auth'
import { isHttp } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import useSettingsStore from '@/store/modules/settings'
import { getTokenByUrl, isEmptyValue} from '@/utils/util'
import usePermissionStore from '@/store/modules/permission'
NProgress.configure({ showSpinner: false });
const whiteList = [ '/auth-redirect', '/bind'];
const baseGoauthUrl = import.meta.env.VITE_APP_GOAUTH_API
const baseSellerUrl = import.meta.env.VITE_APP_SELLER_API
router.beforeEach((to, from, next) => {
    NProgress.start();
    if (getToken() || !isEmptyValue(getTokenByUrl()) ||  window.location.href.indexOf('localhost') != -1 || window.location.href.indexOf('file://') !=-1) {
        if (!isEmptyValue(getTokenByUrl())) {
            setToken(getTokenByUrl())
        }
        to.meta.title && useSettingsStore().setTitle(to.meta.title)
        if (to.path === '/login') {
            next({ path: '/' });
            NProgress.done()
        } else {
                isRelogin.show = false;
                usePermissionStore().generateRoutes().then(accessRoutes => {
                    accessRoutes.forEach(route => {
                            router.addRoute(route) // 动态添加可访问路由表
                    });
                    next({...to, replace: true}) // hack方法 确保addRoutes已完成
                });
            next()
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            window.location.href = `${baseGoauthUrl}oauth/authorize?response_type=token&client_id=seller&redirect_uri=${baseSellerUrl}`
            NProgress.done()
        }
    }
});

router.afterEach(() => {
    NProgress.done()
})